﻿/*
 * OpenDoPE Word Add-In
 * Copyright (C) 2010-2011  Plutext Pty Ltd
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 * For details, see http://www.gnu.org/licenses/gpl-2.0.html
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NLog;

using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;


namespace OpenDoPE_Wed
{

    class ConditionsPartUtils
    {
        static Logger log = LogManager.GetLogger("ConditionsPartUtils");

        public static condition getByID(
            Office.CustomXMLPart conditionsPart,
            string conditionID)
        {
            conditions conditions = new conditions();
            conditions.Deserialize(conditionsPart.XML, out conditions);

            return getByID(conditions, conditionID);
        }

        private static condition getByID(
            conditions conditions,
            string conditionID)
        {
            foreach (condition item in conditions.condition)
            {
                if (item.id.Equals(conditionID))
                {
                    return item;
                }
            }
            return null;
        }


        /// <summary>
        /// Stuff required to create XPath element
        /// (if an entry with this ID exists already,
        /// it will be overwritten)
        /// </summary>
        /// <param name="xpath"></param>
        /// <param name="storeItemID"></param>
        /// <param name="prefixMappings"></param>
        /// <param name="questionID"></param>
        public static void updateConditionsPart(
            Office.CustomXMLPart conditionsPart,
            object xpathref,
            string conditionID)
        {
            //Office.CustomXMLPart xpathsPart = ((WedTaskPane)this.Parent.Parent.Parent).xpathsPart;

            conditions conditions = new conditions();
            conditions.Deserialize(conditionsPart.XML, out conditions);

            condition condition = getByID(conditions, conditionID);
            if (condition == null)
            {
                condition = new condition();
                condition.id = conditionID;
            }
            else
            {
            }

            condition.Item = xpathref;


            // Save it in docx
            string result = conditions.Serialize();
            log.Info(result);
            CustomXmlUtilities.replaceXmlDoc(conditionsPart, result);

        }

    }
}
